package com.chinawlx.wlxteacher.ui.adapter.calendar;




import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;

import com.chinawlx.wlxteacher.ui.fragment.calendar.WLXMonthFragment;
import com.chinawlx.wlxteacher.ui.fragment.calendar.WLXWeekFragment;

import java.util.ArrayList;
import java.util.LinkedHashSet;

/**
 * 作者:吴名
 * 时间:16/9/3
 * 描述:日历月份模式的ViewPager适配器
 */
public class WLXCalendarPagerAdapter extends FragmentPagerAdapter {

    private ArrayList<Fragment> mFragments;
    private LinkedHashSet<String> mTagSet = new LinkedHashSet<>();//存放Fragment对应的Tag(不会重复)
    private FragmentManager mFragmentManager;

    public WLXCalendarPagerAdapter(FragmentManager fm, ArrayList<Fragment> fragments) {
        super(fm);
        this.mFragments = fragments;
        this.mFragmentManager = fm;
    }

    /**
     * 月份模式下,只有3页(显示3个月的)
     */
    @Override
    public int getCount() {
        return mFragments.size();
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    public void setFragment(ArrayList<Fragment> fragments) {
        mFragments = fragments;
    }

    // 生成 Tag
    // 直接从 FragmentPageAdapter 源码里拷贝 Fragment 生成 Tag 的方法
    private String makeFragmentName(int viewId, int index) {
        return "android:switcher:" + viewId + ":" + index;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        mTagSet.add(makeFragmentName(container.getId(), (int) getItemId(position)));
        return super.instantiateItem(container, position);
    }

    public void update() {
        for (String tag : mTagSet) {
            Fragment fragment = mFragmentManager.findFragmentByTag(tag);
            if (fragment == null) return;
            if (fragment instanceof WLXMonthFragment) {
                ((WLXMonthFragment) fragment).update();
            } else if (fragment instanceof WLXWeekFragment) {
                ((WLXWeekFragment) fragment).update();
            }
        }
        notifyDataSetChanged();
    }
}
